"""Deep health check (OBS-04)."""
import logging
import os
import time
from typing import Any

from fastapi import APIRouter, Response, status

logger = logging.getLogger(__name__)

router = APIRouter(prefix="", tags=["health"])


@router.get("/health")
async def liveness() -> dict[str, Any]:
    return {"status": "OK", "service": "eugene-ws"}


@router.get("/health/ready")
async def readiness(response: Response) -> dict[str, Any]:
    checks: dict[str, dict[str, Any]] = {}
    overall_ok = True

    # Neo4j reachability via existing connection factory
    uri = os.environ.get("NEO4J_URI", "")
    if uri:
        start = time.perf_counter()
        try:
            from graph.infra.db.graph_db_connection_factory import (
                GraphDbConnectionFactory,
            )

            driver = GraphDbConnectionFactory.remote_neo4j_instance_from_env()
            driver.verify_connectivity()
            checks["neo4j"] = {
                "ok": True,
                "latency_ms": int((time.perf_counter() - start) * 1000),
            }
        except Exception as exc:
            checks["neo4j"] = {"ok": False, "error": f"{type(exc).__name__}: {exc}"}
        overall_ok &= checks["neo4j"]["ok"]
    else:
        checks["neo4j"] = {"ok": False, "error": "NEO4J_URI not set"}
        overall_ok = False

    if not overall_ok:
        response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE

    return {
        "status": "OK" if overall_ok else "DEGRADED",
        "service": "eugene-ws",
        "checks": checks,
    }
